<template>
  <a-layout>
    <a-layout-content style="padding: 24px;" >
      <div>
        <a-row class="headRow">
          <a-col :span="12">
            <h3>{{ title }}</h3>
          </a-col>
          <a-col>
            <a-button @click="handleUploadExperiment">新建实验</a-button>
          </a-col>
        </a-row>
      </div>
      <!-- 表格内容 -->
      <a-spin :spinning="loading">
        <a-table :columns="columns" :data-source="Data" :pagination="false" :scroll="{y:'35vh'}">
          <template #bodyCell="{column, record}">
            <template v-if="column.key === 'action' ">
              <span>
                <a @click="handleCheckDetail(record)">点击进入</a>
                <a-divider type="vertical" />
              </span>
            </template>
          </template>
        </a-table>

        <a-table :columns="fileTableColumns" :data-source="fileData" :pagination="false" :scroll="{y:'30vh'}">
          <template #bodyCell="{column, record}">
            <template v-if="column.key === 'action' ">
              <span>
                <a-button 
                  :loading="record.downloading" 
                  @click="handleDownloadFile(record)"
                >
                  {{ record.downloading ? `${record.progress}%` : '下载' }}
                </a-button>
                <a-divider type="vertical" />
              </span>
            </template>
          </template>
        </a-table>
      </a-spin>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import { Layout, Table, Button, Space, message } from 'ant-design-vue';
import axiosInstance from "@/axios/axios.js";

export default defineComponent({
  name: 'MyDataExperiment',
  components: {
  },
  data() {
    return {
      loading: false,
      title: '实验列表',
      Data: [],
      columns: [
        {
          title: '实验名',
          dataIndex: 'experiment_name',
          key: 'experiment_name'
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description'
        },
        {
          title: '实验人',
          dataIndex: 'creator',
          key: 'creator'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      fileData: [],
      fileTableColumns: [
        {
          title: "文件名",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "修改时间",
          dataIndex: "modifiedTime",
          key: "modifiedTime"
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: 'action' }
        }
      ]
    };
  },
  async created() {
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查路由参数
    const requiredParams = ['batch_id', 'experiment_set_name', 'experiment_batch_name'];
    const missingParams = requiredParams.filter(param => !this.$route.query[param]);
    if (missingParams.length > 0) {
      message.error('缺少必要的参数');
      this.$router.push('/MyData');
      return;
    }

    // 检查用户信息
    const username = this.$cookies.get("username");
    
    if (!username) {
      message.error('用户信息不完整，请重新登录');
      this.$router.push('/login');
      return;
    }

    // 设置标题
    this.title = `实验列表 - ${this.$route.query.experiment_batch_name}`;

    await this.fetchData();
    await this.getNonDirectoryFilesInfo();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/myData/getExperiments",
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
          data: {
            username: this.$cookies.get("username"),
            dataId: this.$route.query.batch_id,
          },
        });

        if (response.data?.data?.experiments) {
          this.Data = response.data.data.experiments;
          
          // 追加热处理图像数据表项（仅用于跳转）
          const heatTreatmentDataItem = {
            batch_id: "-",
            creator: this.$cookies.get("username"),
            description: "热处理图像数据文件夹",
            experiment_id: "-",
            experiment_name: "-",
            experiment_set_id: "-",
            folder_path: "-",
            xlsx_path: "-"
          };
          this.Data.push(heatTreatmentDataItem);
        } else {
          console.warn("No experiments data in response:", response.data);
          this.Data = [];
        }
      } catch (error) {
        console.error('获取实验数据失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
        }
      } finally {
        this.loading = false;
      }
    },

    async getNonDirectoryFilesInfo() {
      try {
        const relativePath = this.$cookies.get("username") + "/" + 
                           this.$route.query.experiment_set_name + "/" + 
                           this.$route.query.experiment_batch_name;
        const encodeRelativePath = encodeURIComponent(relativePath);
        
        const response = await axiosInstance({
          method: "GET",
          url: "/common/getFilesInfo?relativePath=" + encodeRelativePath,
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
        });

        if (response.data?.data) {
          this.fileData = response.data.data.map(file => ({
            ...file,
            downloading: false,
            progress: 0
          }));
        }
      } catch (error) {
        console.error('获取文件信息失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`获取文件信息失败: ${error.response?.data?.message || error.message}`);
        }
      }
    },

    async handleDownloadFile(record) {
      if (record.downloading) return;

      // 更新文件状态
      const index = this.fileData.findIndex(f => f.name === record.name);
      if (index !== -1) {
        this.fileData[index].downloading = true;
        this.fileData[index].progress = 0;
      }

      try {
        const response = await axiosInstance({
          method: "GET",
          url: record.url,
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
          responseType: "blob",
          onDownloadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              if (index !== -1) {
                this.fileData[index].progress = progress;
              }
            }
          }
        });

        // 创建下载链接
        const blobUrl = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = blobUrl;
        link.setAttribute('download', record.name);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(blobUrl);

        message.success('下载完成');
      } catch (error) {
        console.error('下载文件失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`下载失败: ${error.response?.data?.message || error.message}`);
        }
      } finally {
        // 重置文件状态
        if (index !== -1) {
          this.fileData[index].downloading = false;
          this.fileData[index].progress = 0;
        }
      }
    },

    handleCheckDetail(record) {
      if (record.description === '热处理图像数据文件夹') {
        if (!this.$route.query.batch_id || 
            !this.$route.query.experiment_set_name || 
            !this.$route.query.experiment_batch_name) {
          message.error('缺少必要的参数');
          return;
        }

        this.$router.push({
          path: '/MyData/HeatTreatmentImages',
          query: {
            batch_id: this.$route.query.batch_id,
            experiment_set_name: this.$route.query.experiment_set_name,
            experiment_batch_name: this.$route.query.experiment_batch_name
          }
        });
      } else {
        if (!record.experiment_id) {
          message.error('实验ID不存在');
          return;
        }

        this.$router.push({
          path: '/MyData/Image',
          query: {
            experiment_id: record.experiment_id,
            experiment_set_name: this.$route.query.experiment_set_name,
            experiment_batch_name: this.$route.query.experiment_batch_name,
            experiment_name: record.experiment_name,
          }
        });
      }
    },

    handleUploadExperiment() {
      if (!this.$route.query.experiment_set_id || 
          !this.$route.query.experiment_set_name || 
          !this.$route.query.experiment_batch_name || 
          !this.$route.query.batch_id) {
        message.error('缺少必要的参数');
        return;
      }

      this.$router.push({
        path: '/UploadExperiment',
        query: {
          experiment_set_id: this.$route.query.experiment_set_id,
          experiment_set_name: this.$route.query.experiment_set_name,
          experiment_batch_name: this.$route.query.experiment_batch_name,
          batch_id: this.$route.query.batch_id,
        }
      });
    }
  }
});
</script>

<style scoped>
.headRow {
  margin: 20px;
}
</style>
